from flask import render_template, g

from models import db
from models.index import Product
from views import index_bp


@index_bp.route('/')
def index():
    user = g.user
    shop_car_count = g.shop_car_count
    fruit_list = db.session.query(Product).filter(Product.type == 'fruit').all()
    fruit_list = fruit_list[:4]

    return render_template('index.html', user=user, fruit_list=fruit_list, shop_car_count=shop_car_count)


@index_bp.route('/product_list')
def product_list():
    product_all_list = db.session.query(Product).all()
    fruit_list = []
    vegetable_list = []
    for product in product_all_list:
        if product.type == 'fruit':
            fruit_list.append(product)
        elif product.type == 'vegetable':
            vegetable_list.append(product)
    fruit_list = fruit_list[:5]
    vegetable_list = vegetable_list[:5]
    return render_template('Products.html', fruit_list=fruit_list, vegetable_list=vegetable_list, user=g.user,
                           shop_car_count=g.shop_car_count)


@index_bp.route('/product_detail/<int:product_id>')
def product_detail(product_id):
    product = db.session.query(Product).filter(Product.id == product_id).first()
    return render_template('Product-detailed.html', product=product, user=g.user, shop_car_count=g.shop_car_count)


@index_bp.route('/fruit_all')
def fruit_all():
    product_all_list = db.session.query(Product).all()
    product = [x for x in product_all_list if x.type == 'fruit']

    return render_template('Product-List.html', product=product, user=g.user, is_vegetable=None,
                           shop_car_count=g.shop_car_count)


@index_bp.route('/vegetable_all')
def vegetable_all():
    product_all_list = db.session.query(Product).all()
    product = [x for x in product_all_list if x.type == 'vegetable']
    is_vegetable = True
    return render_template('Product-List.html', product=product, user=g.user, is_vegetable=is_vegetable,
                           shop_car_count=g.shop_car_count)
